package com.yanx.system.web.command;

import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.yanx.common.command.Executor;
import com.yanx.common.core.command.VoidCommand;
import com.yanx.common.exception.BusinessException;
import com.yanx.common.security.SecurityUtils;
import com.yanx.common.security.service.TokenService;
import com.yanx.system.base.command.SysRoleUpdateCmd;
import com.yanx.system.base.domain.manager.SysRoleManager;
import com.yanx.system.base.model.dto.SysRoleDto;
import com.yanx.system.web.query.PremsByUserIdQry;
import com.yanx.system.web.query.RoleKeysByUserIdQry;
import lombok.AllArgsConstructor;

/**
 * 角色信息 修改命令
 *
 * @author: gotanks
 * @create: 2023-5-22
 */
@AllArgsConstructor
public class SystemRoleEditCmd extends VoidCommand {
    private SysRoleDto role;

    @Override
    public void handler(Executor executor) {
        SysRoleManager sysRoleManager = executor.getReceiver(SysRoleManager.class);
        if (sysRoleManager.checkRoleNameUnique(role.getRoleName(), role.getId())) {
            throw new BusinessException("修改角色'{}'失败，角色名称已存在", role.getRoleName());
        }
        if (sysRoleManager.checkRoleKeyUnique(role.getRoleKey(), role.getId())) {
            throw new BusinessException("修改角色'{}'失败，角色权限已存在", role.getRoleName());
        }
//        role.setUpdateBy(getUsername());
        executor.execute(new SysRoleUpdateCmd(role.getId(), role));

        //更新缓存用户权限
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null && loginUser.getUserId() != 1) {
            loginUser.setRoles(executor.execute(new RoleKeysByUserIdQry(loginUser.getUserId())));
            loginUser.setPermissions(executor.execute(new PremsByUserIdQry(loginUser.getUserId())));
            SpringUtil.getBean(TokenService.class).refreshToken(loginUser);
        }
    }
}